package com.polaris.live.utils

import com.google.common.net.InternetDomainName
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.resp.UserResp
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.manager.AppConfigManager
import java.net.URL

/**
 * WebUtils
 *
 * @author Created by lucas on 2023/10/24 13:34
 */
object WebUtils {

    private var safeUrls: Set<String>? = null

    fun formatUrl(url: String): String {
        return if (url.startsWith("http")) {
            url
        } else {
            (AppConfigManager.getConfig(CommonConst.Configs.ossUrl) ?: "") + url
        }
    }

    /**
     * 拼接参数
     */
    fun spliceUrlParams(url: String): String {
        if (!isSafeUrl(url)) {
            return url
        }

        val builder = StringBuilder(url)
        if (url.lastIndexOf("?") == -1) {
            builder.append("?")
        } else {
            builder.append("&")
        }

        builder.append(WebAppConfig(UserManager.getUser()).toParam())

        return builder.toString()
    }

    /**
     * 是否为可信的域名
     */
    fun isSafeUrl(url: String): Boolean {
        val staticUrl = AppConfigManager.getConfig(CommonConst.Configs.ossUrl) ?: ""
        if (url.startsWith(staticUrl)) {
            return true
        }

        val safeUrls = safeUrls ?: let {
            val safeUrl = AppConfigManager.getConfig(CommonConst.Configs.safeUrl)
            val split = safeUrl?.split(",")
            if (split.isNullOrEmpty()) {
                null
            } else {
                split.toSet().apply {
                    safeUrls = this
                }
            }
        } ?: emptySet()

        return safeUrls.any {
            url.startsWith(it)
        }
    }

    /**
     * 是否为安全的url内容，用于消息
     */
    fun isSafeUrlContent(content: String): Boolean {
        if (!isSafeUrl(content)) {
            return false
        }

        return isValidUrl(content)
    }

    /**
     * 是否为有效的url
     */
    fun isValidUrl(text: String): Boolean {
        return try {
            val url = URL(text).toURI()
            val host = url.host
            if (url.path.contains("//") && host.lastIndexOf("http") != -1) {
                return false
            }
            return InternetDomainName.isValid(host)
        } catch (_: Throwable) {
            false
        }
    }

}

data class WebAppConfig(
    val params: Map<String, String>
) {

    constructor(user: UserResp) : this(
        mapOf(
            "accessToken" to (user.token ?: ""),
            "userId" to (user.userId?.toString() ?: ""),
            "appType" to AppConst.APP_TYPE.toString(),
            "platformType" to AppConst.PLATFORM_TYPE.toString(),
            "variantType" to AppConst.VARIANT_TYPE.toString(),
            "buildVersion" to AppModule.getAppVersion().toString(),
            "locale" to (user.profile?.appLanguage ?: user.profile?.language ?: "")
        )
    )

    fun toParam(): String {
        return params.map { "${it.key}=${it.value}" }.joinToString("&")
    }

    fun toJson(): String {
        return JsonUtils.toJson(params)
    }
}